<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination, ElCheckboxGroup, ElCheckbox } from 'element-plus';

// 角色数据
const roleData = ref([]);

// 搜索条件
const searchForm = reactive({
  roleName: '',
  status: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的角色ID
const currentRoleId = ref(null);
// 表单数据
const formData = reactive({
  roleName: '',
  roleDesc: '',
  permissions: [],
  status: true
});

// 权限列表
const permissions = ref([
  { label: '线索管理', value: 'clue:manage' },
  { label: '线索池管理', value: 'clue:pool:manage' },
  { label: '商机管理', value: 'business:manage' },
  { label: '公海池管理', value: 'public:pool:manage' },
  { label: '客户管理', value: 'customer:manage' },
  { label: '课程管理', value: 'course:manage' },
  { label: '活动管理', value: 'activity:manage' },
  { label: '部门管理', value: 'dept:manage' },
  { label: '角色管理', value: 'role:manage' },
  { label: '用户管理', value: 'user:manage' },
  { label: '系统日志', value: 'log:view' }
]);

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '角色名称长度在1到50个字符之间', trigger: 'blur' }
  ]
};

// 表单引用
const roleFormRef = ref(null);

// 加载角色数据
const loadRoleData = () => {
  // 模拟API请求，使用静态数据
  roleData.value = [
    {
      id: 1,
      roleName: '超级管理员',
      roleDesc: '系统最高权限',
      permissions: ['clue:manage', 'clue:pool:manage', 'business:manage', 'public:pool:manage', 'customer:manage', 'course:manage', 'activity:manage', 'dept:manage', 'role:manage', 'user:manage', 'log:view'],
      status: true,
      createTime: '2025-01-01 00:00:00',
      updateTime: '2025-01-01 00:00:00'
    },
    {
      id: 2,
      roleName: '销售经理',
      roleDesc: '负责销售团队管理',
      permissions: ['clue:manage', 'clue:pool:manage', 'business:manage', 'public:pool:manage', 'customer:manage'],
      status: true,
      createTime: '2025-01-10 10:00:00',
      updateTime: '2025-02-15 14:30:00'
    },
    {
      id: 3,
      roleName: '销售人员',
      roleDesc: '负责线索跟进和商机管理',
      permissions: ['clue:manage', 'business:manage', 'customer:manage'],
      status: true,
      createTime: '2025-01-15 09:30:00',
      updateTime: '2025-03-20 16:45:00'
    }
  ];
};

// 计算总数
const total = computed(() => roleData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return roleData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentRoleId.value = row.id;
  Object.assign(formData, { ...row });
  dialogVisible.value = true;
};

// 删除角色
const deleteRole = (row) => {
  if (row.roleName === '超级管理员') {
    ElMessage.warning('超级管理员角色不能删除');
    return;
  }
  
  ElMessageBox.confirm('确定要删除该角色吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = roleData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      roleData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 保存角色
const saveRole = () => {
  roleFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = roleData.value.findIndex(item => item.id === currentRoleId.value);
        if (index !== -1) {
          Object.assign(roleData.value[index], formData, { updateTime: now });
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newRole = {
          id: Date.now(), // 模拟生成唯一ID
          ...formData,
          createTime: now,
          updateTime: now
        };
        roleData.value.push(newRole);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 重置表单
const resetForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
  formData.roleName = '';
  formData.roleDesc = '';
  formData.permissions = [];
  formData.status = true;
  currentRoleId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadRoleData();
});
</script>

<template>
  <div class="role-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 120px;">
            <el-option label="启用" :value="true"></el-option>
            <el-option label="禁用" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="openAddDialog">新增角色</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="currentPageData" stripe style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="250"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.status" disabled size="small"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" link @click="deleteRole(row)" :disabled="row.roleName === '超级管理员'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editMode ? '编辑角色' : '新增角色'"
      width="600px"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="formData.roleDesc" placeholder="请输入角色描述" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="权限设置">
          <el-checkbox-group v-model="formData.permissions">
            <div style="max-height: 300px; overflow-y: auto;">
              <el-checkbox
                v-for="permission in permissions"
                :key="permission.value"
                :label="permission.value"
                style="display: block; margin-bottom: 10px;"
              >
                {{ permission.label }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="formData.status"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role-container {
  padding: 20px;
}

.search-area {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-area {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>